package com.example.blade.activity.browser.temporary

import android.annotation.SuppressLint
import android.content.Intent
import android.content.res.Configuration
import android.net.Uri
import android.os.Bundle
import android.view.KeyEvent
import android.webkit.URLUtil
import android.webkit.WebView
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.content.res.ComplexColorCompat
import cn.vove7.bottomdialog.BottomDialog
import cn.vove7.bottomdialog.builder.buttons
import cn.vove7.bottomdialog.builder.message
import cn.vove7.bottomdialog.builder.title
import com.blankj.utilcode.util.*
import com.drake.channel.receiveEvent
import com.drake.channel.receiveTag
import com.example.blade.Constant
import com.example.blade.InputBox
import com.example.blade.ReaderUtil
import com.example.blade.activity.browser.NestedScrollWebView
import com.example.blade.activity.browser.PointIcon
import com.just.agentweb.AgentWeb
import com.just.agentweb.DefaultWebClient
import com.just.agentweb.MiddlewareWebChromeBase
import com.just.agentweb.MiddlewareWebClientBase
import kotlinx.android.synthetic.main.activity_web_view.*
import me.jingbin.web.ByWebTools
import nico.styTool.R


class WebViewActivity : AppCompatActivity() {

    private val mAgentWeb by lazy {
        AgentWeb.with(this)
            .setAgentWebParent(web_view, FrameLayout.LayoutParams(-1, -1))
            .useDefaultIndicator()
            .setWebView(NestedScrollWebView(this))
            .useMiddlewareWebClient(getMiddlewareWebClient())
            .useMiddlewareWebChrome(getMiddlewareWebChrome())
            /*.setWebViewClient(object : com.just.agentweb.WebViewClient() {
                override fun onPageFinished(view: WebView?, url: String?) {
                    //super.onPageFinished(view, url)
                    ImageUtils.view2Bitmap(view).getPixel(3, 3).apply {
                        BarUtils.setStatusBarColor(this@WebViewActivity, this)
                        if (ReaderUtil.isLightColor(this)) {
                            BarUtils.setStatusBarLightMode(this@WebViewActivity, true)
                        }
                    }
                    *//* setStatusBarVisibility(this@ActiveWeb, false)
                     byWebView.webView.settings.javaScriptEnabled = !url.contains("iqiyi.com")*//*
                    SPUtils.getInstance(Constant.spName).put(restoreUrl, url)
                    nico.styTool.Utils.setToast(text)
                    if (view != null) {
                        if (url != null) {
                            storeHistory(view.title, url)
                        }
                    }
                }
            })*/
            .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)
            .createAgentWeb()
            .ready()
            .go(url)
    }

    private fun getMiddlewareWebChrome() = object : MiddlewareWebChromeBase() {

    }

    private fun getMiddlewareWebClient() = object : MiddlewareWebClientBase() {
        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            if (view != null) {
                synchronized(view) {
                    try {
                        ImageUtils.view2Bitmap(view).getPixel(3, 3).let {
                            BarUtils.setStatusBarColor(this@WebViewActivity, it)
                            if (ReaderUtil.isLightColor(it)) {
                                BarUtils.setStatusBarLightMode(this@WebViewActivity, true)
                            }
                        }
                    } catch (e: Exception) {
                        e.message?.let { nico.styTool.Utils.setToast(it) }
                    }
                    if (url != null) {
                        view.title?.let { storeHistory(it, url) }
                        nico.styTool.Utils.setToast(text)
                    }
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web_view)
        iniView()
        channel()
        ini()
        acceptData()
    }

    private fun acceptData() {
        SPUtils.getInstance(Constant.spName).getString("AcceptData").apply {
            if (this != "") {
                mAgentWeb.webCreator.webView.loadUrl(this)
            }
        }
    }

    @SuppressLint("PrivateResource")
    private fun ini() {
        val webView = mAgentWeb.webCreator.webView
        val view = Bottom_app_bar
        ThreadUtils.runOnUiThread {
            if (SPUtils.getInstance(Constant.spName).contains(restoreUrl)) {
                //BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.design_snackbar_background_color))
                SnackbarUtils.with(view).setMessage("恢复上次浏览?").setAction("恢复") {
                    val url = SPUtils.getInstance(Constant.spName).getString(restoreUrl)
                    if (url != "") {
                        webView.loadUrl(url)
                    }
                }.show(true)
            }
        }
        if (webView != null) {
            ThreadUtils.runOnUiThread {
                val id = R.color.navColorPrimary
                BarUtils.setStatusBarColor(this@WebViewActivity, ContextCompat.getColor(this, id))
            }
            download()
        }
    }

    private fun channel() {
        receiveTag("visibility") {
            Floating_action_button.apply {
                if (isOrWillBeHidden) show() else hide()
            }
        }
    }

    private fun iniView() {

        Floating_action_button.apply {
            setOnClickListener {
                InputBox.Builder(this@WebViewActivity, Hint = arrayOf("搜索戓进入网址"))
                    .setPositiveButton {
                        mAgentWeb.webCreator.webView.loadUrl(ByWebTools.getUrl(InputBox.SaveData))
                        it.dismiss()
                    }.create()
            }
            setOnLongClickListener {
                hide()
                true
            }
        }
        Bottom_app_bar.apply {
            setOnMenuItemClickListener {
                PointIcon(mAgentWeb.webCreator.webView, this@WebViewActivity, it.itemId)
                false
            }
        }
    }

    private fun storeHistory(title: String, url: String) {
        val content = "$title ${url}\n"
        FileIOUtils.writeFileFromString(filePath, content, true)
    }

    private fun download() {
        mAgentWeb.webCreator.webView.setDownloadListener { url, userAgent, contentDisposition, miMeType, _ ->
            //println("$url\n$userAgent\n$contentDisposition\n$miMeType\n$contentLength")
            val name = URLUtil.guessFileName(url, contentDisposition, miMeType)
            val link = if (url.length > 200) "链接太多了,不展示!" else url
            val str = "命名：$name\n\n链接：$link\n\nuserAgent：$userAgent"
            BottomDialog.builder(this) {
                title("下载")
                message(str, selectable = true)
                buttons {
                    positiveButton {
                        startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
                    }
                }
            }
        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        val orientation: Int = newConfig.orientation
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            ScreenUtils.toggleFullScreen(this)
            Floating_action_button.show()
        } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            ScreenUtils.toggleFullScreen(this)
            Floating_action_button.hide()
        }
    }

    /* override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
         super.onActivityResult(requestCode, resultCode, intent)
         byWebView.handleFileChooser(requestCode, resultCode, intent)
     }*/
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            true
        } else super.onKeyDown(keyCode, event)
    }

    override fun onPause() {
        mAgentWeb.webLifeCycle.onPause()
        super.onPause()
    }

    override fun onResume() {
        mAgentWeb.webLifeCycle.onResume()
        super.onResume()
    }

    override fun onDestroy() {
        mAgentWeb.webLifeCycle.onDestroy()
        super.onDestroy()
    }

    companion object {
        private const val url = "https://m.iqiyi.com/v_ulduwjfswo.html"
        private const val restoreUrl = "RestorePage"
        private const val text = "您正在访问第三方网站,请注意安全!"
        val filePath = "${PathUtils.getExternalAppDocumentsPath()}/storeHistory.txt"
    }
}